package com.nitty.cash.loop.ui.fragment

import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.nitty.cash.loop.R
import com.nitty.cash.loop.common.CommonFragment
import com.nitty.cash.loop.configs.NittyApiPath
import com.nitty.cash.loop.configs.NittyApiUrl
import com.nitty.cash.loop.configs.NittyApiUrl.addCommonParams
import com.nitty.cash.loop.databinding.UiPageTabRepayBinding
import com.nitty.cash.loop.event.NittyEventData
import com.nitty.cash.loop.event.NittyEventPointType
import com.nitty.cash.loop.request.IHttpCallback
import com.nitty.cash.loop.ui.activity.OrderPayPinAct
import com.nitty.cash.loop.ui.adapter.OrderRepayAdapter
import com.nitty.cash.loop.utils.helper.NittyOrderHelper
import org.json.JSONObject

/**
 * NittyCash
 * @Author wwdeng
 * @CreateTime: 2024/12/10 14:53
 * @Annotation：还款
 */
class TabRepayFragment: CommonFragment() {
    lateinit var binding: UiPageTabRepayBinding
    private var repayAdapter: OrderRepayAdapter? = null
    override fun getNittyRootView(inflater: LayoutInflater): View {
        binding = UiPageTabRepayBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initNittyView() {
        setNittyTitleBarVisibility(View.VISIBLE)
        setNittyBackBtnVisibility(View.GONE)
        setNittyTextTitleVisibility(View.GONE)
        setNittyRightBtnRes(R.mipmap.img_customer_white)
        setNittyRootBackgroundLableRes(R.mipmap.nitty_withdraw_titlebar_bg)
        setNittyRootParentBackgroundColors(Color.parseColor("#ffffd451"), Color.parseColor("#ffffac17"))

        initOrderRepayRefrashView()
        initOrderRepayRecyclerView()
        addEventPointRequestAction(NittyEventPointType.PAGE.NITTY_PAGE_REPAY_START)
    }

    override fun initNittyListener() {
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog("Repay Page")
            addEventPointRequestAction(NittyEventPointType.CLICK.NITTY_CLICK_CUSTOMER,"Repay Page")
        }
    }

    override fun loadNittyData() {
        val repayList = NittyOrderHelper.getNittyOrderRepayList()
        if (repayList.size == 0){
            repayAdapter?.clear()
            val emptyItem = JSONObject()
            emptyItem.put("isEmptyView",true)
            repayAdapter?.addFirstItem(emptyItem)
            return
        }
        repayAdapter?.data = repayList
    }

    /* 初始化刷新 */
    private fun initOrderRepayRefrashView() {
        binding.repayRefreshLayout.setColorSchemeResources(R.color.theme,R.color.purple_500)
        binding.repayRefreshLayout.setOnRefreshListener {
            publishEventData(NittyEventData(NittyEventData.TYPE.NITTY_ORDER_REFRESH))
        }
    }

    /**
     * 初始化Views
     */
    private fun initOrderRepayRecyclerView(){
        val layoutManager = LinearLayoutManager(requireContext())
        layoutManager.orientation = RecyclerView.VERTICAL
        binding.rvOrderRepay.layoutManager = layoutManager
        repayAdapter = OrderRepayAdapter(binding.rvOrderRepay)
        binding.rvOrderRepay.adapter = repayAdapter!!
        binding.rvOrderRepay.itemAnimator = DefaultItemAnimator()
        repayAdapter?.setOnItemChildClickListener { _, childView, position ->
            val item = repayAdapter!!.getItem(position)
            when(childView.id){
                R.id.textWithdraw -> {//去提现
                    publishEventData(NittyEventData(NittyEventData.TYPE.NITTY_PROCESS_REFRESH))
                    publishEventData(NittyEventData(NittyEventData.TYPE.NITTY_SHOW_HOME))
                }
                R.id.btnOrderRepay -> {//还款
                    val orderId = item.optString("orderId")
                    onNittyOrderPayAction(orderId)
                }
                R.id.imgOrderRepayOpen -> {//展开,收起
                    item.put("isOpen",!item.optBoolean("isOpen",false))
                    repayAdapter?.notifyItemChanged(position)
                }
            }
        }
    }

    /**
     * 订单还款
     * 不减免 normal
     * 积分减免 score
     * 优惠券减免 coupon
     */
    private fun onNittyOrderPayAction(orderId: String){
        showNittyLoading()
        val httpUrl = NittyApiUrl.getHttpUrl()
        val params = JSONObject().addCommonParams().apply {
            put("t8812858f1c5484a8",orderId)
            put("xd304965bcd9478080",NittyApiPath.NITTY_PATH.NITTY_API_LOAN_REPAYMENT_LOOP_URL_PATH)
        }
        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                hiddenNittyLoading()
                val obj = data.optJSONObject("obj")
                if (obj != null){
                    var linkUrl = obj.optString("url","")
                    if (linkUrl.isEmpty()){
                        linkUrl = obj.optString("repayUrl","")
                    }

                    //没有还款链接 - 需要进入还款状态页查询还款状态
                    if (linkUrl.isEmpty()){
                        val thirdOrderId = obj.optString("thirdOrderId")
                        showNittyPayPinAction(orderId,thirdOrderId)
                    } else {
                        showNittyPayLink(linkUrl)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
                hiddenNittyLoading()
            }
        })
    }

    /**
     * 链接还款
     */
    private fun showNittyPayLink(linkUrl: String){
        val uri = Uri.parse(linkUrl)
        val intent = Intent(Intent.ACTION_VIEW, uri)
        startActivity(intent)
    }

    /**
     * pin还款
     */
    private fun showNittyPayPinAction(orderId: String,thirdOrderId: String){
        OrderPayPinAct.start(requireContext(),orderId,thirdOrderId)
    }

    override fun onNittyPublishEvent(event: NittyEventData) {
        super.onNittyPublishEvent(event)
        when(event.eventType){
            NittyEventData.TYPE.NITTY_ORDER_REFRESHED -> {
                loadNittyData()
            }
            NittyEventData.TYPE.NITTY_ORDER_FINISHED -> {
                hiddenNittyLoading()
            }
            else -> {

            }
        }
    }

    override fun hiddenNittyLoading() {
        super.hiddenNittyLoading()
        binding.repayRefreshLayout.isRefreshing = false
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(NittyEventPointType.PAGE.NITTY_PAGE_REPAY_END)
    }
}